package com.zhulin.android.edoctor.fragment;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.zhulin.android.edoctor.R;
import com.zhulin.android.edoctor.db.DBDoctorDBHelp;
import com.zhulin.android.edoctor.jsonobject.JOCaseInfoModel;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

public class FragmentUploadEditItem extends BaseFragment implements OnClickListener{

	private ImageView imageView01,imageView02;

//	private final int TYPE_PHOTO_CAMER=0;
//	private final int TYPE_PHOTO_PHOTOS=1;
//	private final int TYPE_PHOTO_PICCUT=2;
//	
	
	private final int TYPE_PHOTO_01_CAMER=101;
	private final int TYPE_PHOTO_01_PHOTOS=102;
	
	private final int TYPE_PHOTO_02_CAMER=201;
	private final int TYPE_PHOTO_02_PHOTOS=202;
	
	private Spinner spinnerSex,spinnerAge;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v=inflater.inflate(R.layout.fragment_upload_caseitem_edit, container, false);
		
		initView(v);
		loadData();
		
		
		return v;
	}
	
	private void bindSpinnerAge(){
		List<String> strings=new ArrayList<String>();
		for(int i=0;i<100;i++){
			strings.add(i+"");
		}
		ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, strings);
		arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinnerAge.setAdapter(arrayAdapter);
	}

	public void startCapture(Uri uri,int requestCode){
		Intent intent = new Intent("com.android.camera.action.CROP");  
		if(uri!=null)
			intent.setDataAndType(uri, IMAGE_UNSPECIFIED);  
		else{
			intent.setDataAndType(Uri.fromFile(new File("temp.jpg")), IMAGE_UNSPECIFIED);
		}
        intent.putExtra("crop", "true");  
        intent.putExtra("aspectX", 1);  
        intent.putExtra("aspectY", 1);  
        intent.putExtra("outputX", 480);  
        intent.putExtra("outputY", 320);  
        intent.putExtra("return-data", true);  
        startActivityForResult(intent, requestCode+1000);  
	}


	private Bitmap mBitmap01;
	private Bitmap mBitmap02;
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		//super.onActivityResult(requestCode, resultCode, data);

		getActivity();
		if(resultCode!=Activity.RESULT_OK ){
			return;
		}else if(data==null){
			Toast.makeText(getActivity(), "拍照失败,可能没有插入SD卡", 1).show();
			return;
		}
		
		if(requestCode<1000){
			Uri originalUri = data.getData();
			if(originalUri==null){
				originalUri=Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "temp.jpg"));
			}
			startCapture(originalUri,requestCode);
			return;
		}
		getActivity().getContentResolver();
		
		requestCode=requestCode-1000;
		if (requestCode == TYPE_PHOTO_01_CAMER || requestCode==TYPE_PHOTO_02_CAMER)
		{
			try
			{
				Uri uri= data.getData();

				// 将图片内容解析成字节数组
				//mContent = Utils.readStream(resolver.openInputStream(Uri.parse(originalUri.toString())));
				
				Bundle extras = data.getExtras();
				extras.get("data");
				// 将字节数组转换为ImageView可调用的Bitmap对象
				if(requestCode == TYPE_PHOTO_01_CAMER)
				{
					//mBitmap01 = Utils.getPicFromBytes(mContent, null);
					mBitmap01=(Bitmap) extras.get("data");
					imageView01.setImageBitmap(mBitmap01);
				}else if(requestCode==TYPE_PHOTO_02_CAMER){
					//mBitmap02 = Utils.getPicFromBytes(mContent, null);
					mBitmap02=(Bitmap) extras.get("data");
					imageView02.setImageBitmap(mBitmap02);
				}
				// //把得到的图片绑定在控件上显示
			} catch ( Exception e )
			{
			}

		} else if (requestCode == TYPE_PHOTO_01_PHOTOS || requestCode==TYPE_PHOTO_02_PHOTOS)
		{
			try
			{
				Bundle extras = data.getExtras();

				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				if(requestCode == TYPE_PHOTO_01_PHOTOS)
				{
					mBitmap01 = (Bitmap) extras.get("data");
					mBitmap01.compress(Bitmap.CompressFormat.JPEG, 100, baos);
					imageView01.setImageBitmap(mBitmap01);
				}else if(requestCode==TYPE_PHOTO_02_PHOTOS){
					mBitmap02 = (Bitmap) extras.get("data");
					mBitmap02.compress(Bitmap.CompressFormat.JPEG, 100, baos);
					imageView02.setImageBitmap(mBitmap02);
				}
				baos.toByteArray();

			} catch ( Exception e )
			{
				// TODO Auto-generated catch block
				//e.printStackTrace();
			}
			// 把得到的图片绑定在控件上显示
		}



	}

	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.imgCamer01:{
			loadCamerPicture(TYPE_PHOTO_01_CAMER);
			break;
		}
		case R.id.imgCamer02:{
			loadCamerPicture(TYPE_PHOTO_02_CAMER);
			break;
		}case R.id.imgBtnDelete01:{
			if(mBitmap01!=null)
			{
				mBitmap01.recycle();
			}
			imageView01.setImageBitmap(null);
			break;
		}case R.id.imgBtnDelete02:{
			if(mBitmap02!=null)
			{
				mBitmap02.recycle();
			}
			imageView02.setImageBitmap(null);
			break;
		}case R.id.imgBtnPhoto01:{
			loadPhotoPicture(TYPE_PHOTO_01_PHOTOS);
			break;
		}case R.id.imgBtnPhoto02:{
			loadPhotoPicture(TYPE_PHOTO_02_PHOTOS);
			break;
		}case R.id.btnSaveToLocation:{
			saveToLocation();
			break;
		}case R.id.btnSaveToServer:{
			saveToServer();
			break;
		}
		}
	}
	
	private EditText edtPlace,edtSelftDescript,edtPictureDescription,edtName,edtFunction,edtResult;
	
	private Button btnSaveToLocation,btnSaveToServer;
	private void initView(View v){
		imageView01=(ImageView)v.findViewById(R.id.imageView1);
		imageView02=(ImageView)v.findViewById(R.id.imageView2);

		v.findViewById(R.id.imgCamer01).setOnClickListener(this);
		v.findViewById(R.id.imgCamer02).setOnClickListener(this);

		v.findViewById(R.id.imgBtnPhoto01).setOnClickListener(this);
		v.findViewById(R.id.imgBtnPhoto02).setOnClickListener(this);

		v.findViewById(R.id.imgBtnDelete01).setOnClickListener(this);
		v.findViewById(R.id.imgBtnDelete02).setOnClickListener(this);
		
		btnSaveToLocation=(Button) v.findViewById(R.id.btnSaveToLocation);
		btnSaveToServer=(Button) v.findViewById(R.id.btnSaveToServer);
		
		btnSaveToLocation.setOnClickListener(this);
		btnSaveToServer.setOnClickListener(this);
		
		spinnerAge=(Spinner) v.findViewById(R.id.spinnerAge);
		spinnerSex=(Spinner) v.findViewById(R.id.spinnerSex);
		
		spinnerAge=(Spinner) v.findViewById(R.id.spinnerAge);
		spinnerSex=(Spinner) v.findViewById(R.id.spinnerSex);
		
		edtPlace=(EditText)v.findViewById(R.id.edtPlace);
		edtSelftDescript=(EditText)v.findViewById(R.id.edtSelftDesription);
		edtPictureDescription=(EditText)v.findViewById(R.id.edtPictureDescription);
		edtName=(EditText)v.findViewById(R.id.edtName);
		edtFunction=(EditText)v.findViewById(R.id.edtFunction);
		edtResult=(EditText)v.findViewById(R.id.edtResult);
	}
	
	private void loadData(){
		String strName= getArguments().getString("data");
		edtName.setText(strName);
		if(strName==null || strName.length()==0){
			edtName.setEnabled(true);
		}else{
			edtName.setEnabled(false);
		}
		
		bindSpinnerAge();
	}
	/**
	 * 保存到本地
	 */
	private void saveToLocation(){
		JOCaseInfoModel caseInfoModel=new JOCaseInfoModel();
		caseInfoModel.setPlace(edtPlace.getText().toString());
		caseInfoModel.setSelftDescription(edtSelftDescript.getText().toString());
		caseInfoModel.setPictureDescription(edtPictureDescription.getText().toString());
		caseInfoModel.setName(edtName.getText().toString());
		caseInfoModel.setFunction(edtFunction.getText().toString());
		caseInfoModel.setResult(edtResult.getText().toString());
		
		DBDoctorDBHelp dbDoctorDBHelp=new DBDoctorDBHelp(getActivity());
		try {
			if(dbDoctorDBHelp.getDaoMyselftCase().create(caseInfoModel)>0){
				Toast.makeText(getActivity(), "保存成功", 1).show();
				getFragmentManager().popBackStack();
			}else{
				Toast.makeText(getActivity(), "保存失败", 1).show();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			dbDoctorDBHelp.close();
		}
	}
	
	/**
	 * 上传病例
	 */
	private void saveToServer(){
		
	}
	
	public static final String IMAGE_UNSPECIFIED = "image/*"; 
	private void loadPhotoPicture(int requestCode){
		Intent getImage = new Intent(Intent.ACTION_GET_CONTENT);
		getImage.addCategory(Intent.CATEGORY_OPENABLE);
		getImage.setType("image/*");
		startActivityForResult(getImage, requestCode);
		
	}

	public void loadCamerPicture(int request){
		Intent getImageByCamera = new Intent("android.media.action.IMAGE_CAPTURE");
		//getImageByCamera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "temp.jpg"))); //本行视情况删除 
		startActivityForResult(getImageByCamera, request);
		
	}
}
